
package com.shop.cloud.mall.admin.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shop.cloud.common.core.util.R;
import com.shop.cloud.mall.admin.service.DistributionOrderService;
import com.shop.cloud.mall.admin.service.DistributionUserService;
import com.shop.cloud.mall.common.constant.MallConstants;
import com.shop.cloud.mall.common.entity.DistributionUser;
import com.shop.cloud.mall.common.entity.UserWithdrawRecord;
import com.shop.cloud.mall.admin.mapper.UserWithdrawRecordMapper;
import com.shop.cloud.mall.admin.service.UserWithdrawRecordService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

/**
 * 用户提现记录
 *
 * @author
 * @date 2021-05-10 14:20:02
 */
@Service
@AllArgsConstructor
public class UserWithdrawRecordServiceImpl extends ServiceImpl<UserWithdrawRecordMapper, UserWithdrawRecord> implements UserWithdrawRecordService {

	private final DistributionUserService distributionUserService;
	private final DistributionOrderService distributionOrderService;
	@Override
	public IPage<UserWithdrawRecord> page1(IPage<UserWithdrawRecord> page, UserWithdrawRecord userWithdrawRecord) {
		return baseMapper.selectPage1(page,userWithdrawRecord);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public R updateStatus(UserWithdrawRecord userWithdrawRecord) {
		String status = userWithdrawRecord.getStatus();
		String verifyDetail = userWithdrawRecord.getVerifyDetail();
		userWithdrawRecord = baseMapper.selectById(userWithdrawRecord);
		if(MallConstants.USER_WITHDRAW_RECORD_STATUS_1.equals(status)){
			if(MallConstants.USER_WITHDRAW_TYPE_1.equals(userWithdrawRecord.getWithdrawType())){
				DistributionUser distributionUser = distributionUserService.getById(userWithdrawRecord.getUserId());
				//校验申请金额是否小于等于用户可提现额度
				//先获取分销员的冻结金额
				BigDecimal frozenAmount = distributionOrderService.getDistributionUserFrozenAmount(userWithdrawRecord.getUserId());
				if(distributionUser.getCommissionTotal().subtract(distributionUser.getCommissionWithdrawal()).subtract(frozenAmount)
						.compareTo(userWithdrawRecord.getApplyAmount()) == -1){
					//(累计佣金金额-已提现佣金金额-冻结金额)>=申请额度才合法，否则不能提现
					return R.failed("该用户可提现额度不够申请额度");
				}
				//审核通过，需更新用户已提现佣金额度
				distributionUserService.updateCommissionWithdrawal(userWithdrawRecord.getUserId(),userWithdrawRecord.getApplyAmount());
			}
		}
		userWithdrawRecord.setStatus(status);
		userWithdrawRecord.setVerifyDetail(verifyDetail);
		return R.ok(baseMapper.updateById(userWithdrawRecord));
	}
}
